#!/user/bin/env python3
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# @File : conftest.py
# @Time : 2022-06-23 11:41
# @Author : mojin
# @Email : 397135766@qq.com
# @Software : PyCharm
#-------------------------------------------------------------------------------
import pytest,allure,json
from common.csv_data import write_csv_list
import time
from time import strftime
from time import gmtime
from common.operation_excle import operation_excle
from common.database_db import DataBase_db

# fixture传参
# scope参数有四种，分别是'function','module','class','session'，默认为function。
# function：每个test都运行，默认是function的scope
# class：每个class的所有test只运行一次
# module：每个module的所有test只运行一次
# session：每个session只运行一次


@pytest.fixture(scope="session")
def drivers():  #使用项目中的drivers方法就行了，移动到项目里就不用复制这个函数了，其他函数复制到项目conftest中

    global dri,dev
    dev =['devices001',"devices002"]
    dri=[]
    return dri,dev


@pytest.fixture(scope="session",autouse=True)
def dev_srt_naem(drivers):#将多个设备序列号，连为一个字符串
    dev_name_srt=''
    for i in drivers[1]:
        dev_name_srt="%s_%s"%(dev_name_srt,i)
    return dev_name_srt[1:]



@pytest.fixture(scope='session',autouse=True)
def total_calculation(dev_srt_naem):  #汇总每个模块的数据
    dic_data_total=[]
    starttime = int(time.time())
    formatTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(starttime))
    dic_data = {
        'module_tets': '项目测试总耗时',
        'dev_srt_naem':dev_srt_naem,
        'starttime': '',
        'endtime': '',
        'testtime': ''
    }
    dic_data.update({
        'starttime': formatTime
    })
    yield dic_data_total

    endtime = int(time.time())
    formatTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(endtime))
    dic_data.update({
        'endtime': formatTime,
        'testtime': (strftime("%H:%M:%S", gmtime(endtime - starttime)))

    })
    dic_data_total.append(dic_data)


    #print(dic_data_total)
    header_data=''
    dic_data_list=[]#每个模块数据列表
    for dic_data in dic_data_total:
        header_data=list(dic_data.keys())
        dic_data_list.append(list(dic_data.values()))



    runtime = time.strftime("%Y%m%d%H%M%S", time.localtime())
    #path: str, sheetStr, info, data
    #path_excle='./excle-report/%s_%s.xlsx'%(dev_srt_naem,runtime,)
    path_excle = './target/%s.xlsx' % (dev_srt_naem)
    header_data=['测试项','测试设备','开测时间','结束时间','测试耗时']
    operation_excle.write_to_excel(path_excle,'%s_项目耗时统计'%runtime,header_data,dic_data_list)#'%s_项目耗时统计'%runtime



    #path_csv='./excle-report/%s_%s.csv' % (dev_srt_naem, runtime,)
    path_csv='./target/%s.csv' % (dev_srt_naem)
    write_csv_list(path_csv,dic_data_list)
    time.sleep(1)
    with allure.step('项目耗时统计'):
        allure.attach.file(path_csv, name=path_csv,
                           attachment_type=allure.attachment_type.CSV)  # 测试步骤中添加一张图片或视频

    # with allure.step('项目耗时统计'):
    #     allure.attach(
    #         json.dumps(dic_data_list, ensure_ascii=False, indent=4),
    #         "附件内容",
    #         allure.attachment_type.JSON,
    #     )
    #



@pytest.fixture(scope='module',autouse=True)
def calculation(total_calculation,dev_srt_naem):#获取每个模块的数据

    starttime = int(time.time())
    formatTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(starttime))
    dic_data={
    'module_tets': '',
    'dev_srt_naem': dev_srt_naem,
	'starttime': '',
	'endtime': '',
	'testtime': ''
}
    dic_data.update({
        'starttime':formatTime
    })
    yield dic_data

    endtime = int(time.time())
    formatTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(endtime))
    dic_data.update({
        'endtime':formatTime,
        'testtime':(strftime("%H:%M:%S", gmtime(endtime - starttime)))

    })
    total_calculation.append(dic_data)



@pytest.fixture(scope="session")
def get_db():

    try:
        db = DataBase_db()
        yield db
    finally:
        db.close()

@pytest.fixture(scope="function")
def drives():
    import uiautomator2 as u2

    d = u2.connect()
    d.implicitly_wait(20)  # 设置隐式等待时间，默认20s
    mv_path = './screen/test_0001.mp4'
    time.sleep(2)
    d.screenrecord(mv_path)

    yield d

    time.sleep(2)
    d.screenrecord.stop()
    time.sleep(2)
    with allure.step('录屏：'):
        allure.attach.file(mv_path, name='录屏文件', attachment_type=allure.attachment_type.MP4)


